import { useRef, useState } from 'react'
import { allAreaList, allCityList, allProvinceList } from '@hs-admin/utils'
import CommonTree from '@/views/ShoppingCart/components/CommonTree.tsx'
import { Modal } from 'antd'
import { createScopeDetailItem, editScopeDetailItem } from '@/api/shoppingCart.ts'

const allCodeNameMap: Record<string, string> = {}

const levelOneData = allProvinceList.map((item) => {
  allCodeNameMap[item.value] = item.label
  return {
    title: item.label,
    key: item.value
  }
})
const levelTwoData = allProvinceList.map((item) => ({
  title: item.label,
  key: item.value,
  children: (allCityList[item.value as string] ?? []).map((it) => {
    allCodeNameMap[it.value] = `${item.label}-${it.label}`
    return {
      title: it.label,
      key: it.value
    }
  })
}))
const levelThreeData = allProvinceList.map((item) => ({
  title: item.label,
  key: item.value,
  children: (allCityList[item.value as string] ?? []).map((it) => ({
    title: it.label,
    key: it.value,
    children: (allAreaList[it.value as string] ?? []).map((child) => {
      allCodeNameMap[child.value] = `${item.label}-${it.label}-${child.label}`
      return {
        title: child.label,
        key: child.value
      }
    })
  }))
}))

const AreaMap = {
  1: levelOneData,
  2: levelTwoData,
  3: levelThreeData
}

const useEditAreaScope = () => {
  const [areaLevel, setAreaLevel] = useState<1 | 2 | 3>(3)

  const parentId = useRef('')
  const selfId = useRef('')
  const callFun = useRef(() => {
    console.log('do nothing')
  })
  const [open, setOpen] = useState(false)

  const treeAreaData = AreaMap[areaLevel]
  const [areaList, setAreaList] = useState<Array<string>>([])

  return {
    EditAreaScope: (
      <Modal
        title="区域范围选择"
        open={open}
        onOk={async () => {
          if (selfId.current) {
            await editScopeDetailItem(selfId.current, {
              values: areaList.map((it) => ({
                name: allCodeNameMap[it],
                value: it
              }))
            })
          } else {
            await createScopeDetailItem({
              type: 'pca',
              sub_scope_id: parentId.current,
              values: areaList.map((it) => ({
                name: allCodeNameMap[it],
                value: it
              }))
            })
          }
          setOpen(false)
          callFun.current()
        }}
        onCancel={() => {
          setOpen(false)
        }}>
        <div className="max-h-70vh">
          <CommonTree
            disabled={false}
            defaultExpandedKeys={[]}
            checkedKeys={areaList}
            treeData={treeAreaData}
            onCheck={(value) => {
              if (value.length) {
                let finalArr: Array<string> = []
                const maps = Object.groupBy(value, (it) => it.slice(0, 2))
                Object.keys(maps).forEach((key) => {
                  if (maps[key].includes(`${key}0000`)) {
                    finalArr.push(`${key}0000`)
                  } else {
                    const secondMaps = Object.groupBy(maps[key], (it) => it.slice(0, 4))
                    Object.keys(secondMaps).forEach((second) => {
                      if (secondMaps[second].includes(`${second}00`)) {
                        finalArr.push(`${second}00`)
                      } else {
                        finalArr = finalArr.concat(secondMaps[second])
                      }
                    })
                  }
                })
                setAreaList(finalArr)
              } else {
                setAreaList(value)
              }
            }}
          />
        </div>
      </Modal>
    ),
    openModal: (
      parent: string,
      self: string,
      oldValues: Array<{
        name: string
        value: string
      }>,
      call: () => void,
      level: 1 | 2 | 3 = 3
    ) => {
      setAreaLevel(level)
      parentId.current = parent
      selfId.current = self
      callFun.current = call
      setAreaList(oldValues.map((it) => it.value))
      setOpen(true)
    }
  }
}

export default useEditAreaScope
